<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2017/5/30
 * Time: 20:47
 */

namespace Home\Logic;
use Think\Exception;
vendor('WxPay');
vendor('Wxpay.WxPay_Notify');
vendor('Wxpay.WxPay_Api');
vendor('Wxpay.log');
class PayLogic
{

    //处理余额支付逻辑
    public function  payByUserMoney($order_id, $user_id){

        $user = M('users')->where(array('user_id'=>$user_id))->find();
        $order = M('order')->where(array('order_id'=>$order_id, 'is_delete'=>0))->find();
        if(!$user){
            return  array('status'=>-1, 'msg'=>'用户信息不合法');
        }
        if(!$order){
            return  array('status'=>-1, 'msg'=>'未找到该条订单');
        }
        //验证订单状态是否未未支付
        if($order['pay_status'] == 1){
            return  array('status'=>-1, 'msg'=>'该订单已支付');
        }
        //普通商品购买
        if($order['type'] == 1) {
            //判断用户账户余额是否足够
            if($user['user_money'] + $user['rebate_money'] < $order['order_amount'])
                return  array('status'=>-5, 'msg'=>'帐号余额不足', 'order_id'=> $order_id);

            $model = M();
            $model->startTrans();
            try {

                $user_money = $user['user_money'];
                //减少帐号余额
                if($user['rebate_money'] >= $order['order_amount']) { //如果返利金额大于订单应付金额直接用返利金额
                    $model->table('tp_users')->where(array('user_id' => $user['user_id']))->setDec('rebate_money', $order['order_amount']);
                }
                else{ //使用余额和返利金额一起支付  先将返利金额清零
                    $rebate_money = $user['rebate_money'];
                    $model->table('tp_users')->where(array('user_id' => $user['user_id']))->setDec('rebate_money', $rebate_money);
                    $model->table('tp_users')->where(array('user_id' => $user['user_id']))->setDec('user_money', $order['order_amount'] - $rebate_money);
                }
                    //返利给上级用户
                $userLogic = new UserLogic();
                $moneyLogic = new MoneyLogLogic();
                //获取返利比例    移动到确认收货
     /*           $rebate = M('config')->where(array('id' => 73))->getField('value');
                $lastUser = $userLogic->getLastUser($user_id);
                if ($lastUser) {
                    $userLogic->rebateLastUser((double)$rebate * $order['order_amount'], $user_id);

                    $lastUserMoney = M('users')->where(array('user_id'=>$lastUser['user_id']))->getField('user_money');
                    //记录到moneyLog表中需要记录两条数据一条当前用户支出一条上级用户收入返利
//            ($user_id, $score_id, $type, $put_type, $money, $current_money,$remark)
                    //获取上级用户
                    $moneyLogic->addMoneyLog($lastUser['user_id'], $user_id, 1, 0, $order['order_amount'] * $rebate, $lastUserMoney, '下级用户使用余额购买商品返利');
                }*/
                $moneyLogic->addMoneyLog($user_id, $user_id, 2, 1, $order['order_amount'], $user_money, '用户使用余额购买商品');
//                if($user['user_type'] == 1)
//                    $moneyLogic->addAgentLog($user['user_id'], $order['order_amount'], '代理商'.$user['nickname'].'使用余额购买商品');
                update_pay_status($order['order_sn']);
                $this->addSalesSum($order_id);
                //修改订单支付方式
                $order['pay_name'] = '余额支付';
                $order['pay_status'] = 1;
                $order['order_status'] = 1;//已经确认
                $model->table('tp_order')->where(array('order_id'=>$order_id))->save($order);
                $model->commit();

//            M('Order')->where('order_id=' . $order['order_id'])->save(array('pay_name'=>'余额支付'));
                return array('status' => 1, 'msg' => '购买成功');
            }
            catch (Exception $e){
                    $model->rollback();
                    return 3;
                }
        }
        else{//特殊商品需要返利  在take_spec_goods_log表中添加数据

            if($user['user_money'] < $order['order_amount'])
                return  array('status'=>-1, 'msg'=>'帐号余额不足');
            //获取特殊商品id
            $goods_id = M('OrderGoods')->where(array('order_id'=>$order['order_id']))->getField('goods_id');
            //判断是否购买该免费商品
        /*    if(M('TakeSpecGoodsLog')->where(array('user_id'=>$user['user_id'], 'goods_id'=>$goods_id))->count())
                return array('status'=>-1, 'msg'=>'每个用户只能领取一次');*/

            $model = M();
            $model->startTrans();
            try {

                //修改订单状态
                $user_money = $user['user_money'];
                $user['user_money'] -= $order['order_amount'];
                $model->table('tp_users')->where(array('user_id'=>$user['user_id']))->setDec('user_money',$order['order_amount']);
                //返利给上级用户
                $userLogic = new UserLogic();
                $moneyLogic = new MoneyLogLogic();

                $moneyLogic->addMoneyLog($user_id, $user_id, 2, 1, $order['order_amount'], $user_money, '用户使用余额购买特殊商品');
                //添加记录到take_spec_goods_log 表中标记 该用户已领取该商品无法再次领取或购买
//                $this->addTakeSpecGoodsLog($user_id, $goods_id, 0);
                //修改订单支付方式
                $order['pay_name'] = '余额支付';
                $order['pay_status'] = 1;
                $order['order_status'] = 1;//已经确认
                $order['pay_time'] = time();
                //累计消费
                $model->table('tp_users')->where(array('user_id'=>$user['user_id']))->setInc('total_amount',$order['order_amount']);
                $model->table('tp_order')->where(array('order_id'=>$order_id))->save($order);
                $model->commit();
                return array('status' => 1, 'msg' => '购买成功');
            }
            catch (Exception $e){
                    $model->rollback();
                    return 3;
                }
        }


        return array('status'=>-1, 'msg'=>'购买失败');



    }


    public function  addTakeSpecGoodsLog($user_id, $goods_id, $type){

        $data = array(
            'user_id'   => $user_id,
            'goods_id'  => $goods_id,
            'type'      => $type,
            'add_time'  => time()
        );
        M('TakeSpecGoodsLog')->add($data);

    }

    /**
     * @param $order_number 订单编号
     * @param $money 总金额
     * @return int 0余额不足 1支付成功 2支付失败
     */
    public function weChatPaySuccess($order_number,$money)
    {
        $where['order_sn']=':order_sn';
        $bind[':order_sn']=$order_number;
        //购买
        $order = M('Order')->where($where)->bind($bind)->find();
        $recharge_order = D('RechargeOrder')->where($where)->bind($bind)->find();
        $logHandler= new \CLogFileHandler("./logs/".date('Y-m-d').'.log');
        $log = \Log::Init($logHandler, 15);
//        $log->DEBUG('sql:'.D('Order')->getLastSql());
        if($order) {
            $log->DEBUG('sql:'.'in');
            if ($order['pay_status'] == 0 && is_numeric($money) && $order['order_amount']-$order['user_money'] <= $money) {
//            if($order['pay_status'] == 0 && is_numeric($money)) {
                return $this->payByWechat($order['order_id']);
            }
        }
        else if($recharge_order){
            if($recharge_order['state'] == 0 && is_numeric($money) && $recharge_order['money'] <= $money) {
                return $this->rechargeSuccess($recharge_order['id']);//充值成功
            }
        }
        return 2;
    }

    public function rechargeSuccess($recharge_id){

        $recharge = M('RechargeOrder')->where(array('id'=> $recharge_id))->find();
        $user = M('Users')->where(array('user_id'=>$recharge['user_id']))->find();
        $model = M();
        try {
            $userLogic = new UserLogic();
            $recharge['state'] = 1;
            M('RechargeOrder')->save($recharge);
            $userLogic->agentByUserId($user['user_id'], $recharge['money']);

            //记录到充值记录中
            $logData = array('user_id'=> $user['user_id'], 'money'=> $recharge['money'], 'remark'=>'用户'.$user['nickname'].'充值','user_money'=>$user['rebate_money']+$recharge['money']);
            M('RechargeLog')->add($logData);
            $model->commit();

        } catch (Exception $e) {
            $logHandler= new \CLogFileHandler("./logs/".date('Y-m-d').'.log');
            $log = \Log::Init($logHandler, 15);
            $log->DEBUG('error:'.$e->getMessage());
            $model->rollback();
            return 2;
        }


    }

    /**在万企商城通过微信支付成功
     * @param $order_id 订单id
     * @return int 0余额不足 1支付成功 2支付失败
     */
    public function payByWechat($order_id)
    {
        $order = M('Order')->where(array('order_id'=>$order_id))->find();
        $user = D('Users')->where(array('user_id'=>$order['user_id']))->find();

        $model = M();
        try {
            //商品返利
            if($order['type'] == 1) {
                update_pay_status($order['order_sn']);
                //返利给上级用户
                $userLogic = new UserLogic();
                $moneyLogic = new MoneyLogLogic();
                //修改订单支付方式
                $order['pay_name'] = '微信支付';
                $order['pay_status'] = 1;
                $order['order_status'] = 1;//已经确认

                if($order['user_money'] != 0){
                    $user['user_money'] = 0;
                    $user['rebate_money'] = 0;
                    M('users')->save($user);
                }

                M('Order')->save($order);
                $this->addSalesSum($order_id);
                $moneyLogic->addMoneyLog($order['user_id'], $order['user_id'], 2, 1, $order['order_amount'], $user['user_money'], '用户使用微信支付购买商品');
            }
            else{
                //获取特殊商品id
                $goods_id = M('OrderGoods')->where(array('order_id'=>$order['order_id']))->getField('goods_id');
                //修改订单状态
//                M('order')->where(array('order_id'=>$order['order_id']))->save(array('pay_status'=>1,'pay_time'=>time()));
                //返利给上级用户
                $userLogic = new UserLogic();
                $moneyLogic = new MoneyLogLogic();
                //获取返利比例
                $rebate = M('config')->where(array('id' => 73))->getField('value');
                $lastUser = $userLogic->getLastUser($order['user_id']);
                if($lastUser) {
                    $userLogic->rebateLastUser((double)$rebate * $order['order_amount'], $order['user_id']);
                    //记录到moneyLog表中需要记录两条数据一条当前用户支出一条上级用户收入返利
//            ($user_id, $score_id, $type, $put_type, $money, $current_money,$remark)
                    //获取上级用户
                    $moneyLogic->addMoneyLog($lastUser['user_id'], $order['user_id'], 2, 0, $order['order_amount'] * $rebate, $lastUser['user_money'], '下级用户使用微信支付购买商品返利');
                }
//                微信支付不需要记录MoneyLog
                $moneyLogic->addMoneyLog($order['user_id'], $order['user_id'], 2, 1, $order['order_amount'], $user['user_money'], '用户使用微信支付购买商品');
                //添加记录到take_spec_goods_log 表中标记 该用户已领取该商品无法再次领取或购买
//                $this->addTakeSpecGoodsLog($order['user_id'], $goods_id, 0);
                //修改订单支付方式
                $order['pay_name'] = '微信支付';
                $order['pay_status'] = 1;
                $order['order_status'] = 1;//已经确认
                $order['pay_time'] = time();
                $this->addSalesSum($order_id);
                M('Order')->save($order);
                //累计消费
                M('users')->where(array('user_id'=>$order['user_id']))->setInc('total_amount', $order['order_amount']);
                $this->addSalesSum($order_id);
            }
            $model->commit();
            return 1;
        } catch (Exception $e) {
            $logHandler= new \CLogFileHandler("./logs/".date('Y-m-d').'.log');
            $log = \Log::Init($logHandler, 15);
            $log->DEBUG('error:'.$e->getMessage());
            $model->rollback();
            return 2;
        }
    }

    /**
     *
     */

    public function  addSalesSum($order_id){

        $goodsList = M('OrderGoods')->where(array('order_id'=>$order_id))->select();

        //遍历购买商品列表将销量和月销量加上购买数量
        foreach ($goodsList as $key => $val){
            M('Goods')->where(array('goods_id'=>$val['goods_id']))->setInc('sales_month', intval($val['goods_num'])); //增加月销量
        }

    }


    /**
     * 余额退款处理逻辑
     * @param $userId 用户ID
     * @param $money 退款金额
     */
    public function refundByUserMoney($userId, $money){
        $moneyLogic = new MoneyLogLogic();
        $user = M('users')->where(array('user_id'=> $userId))->find();
        if($user){
            M('users')->where(array('user_id'=> $userId))->setInc('rebate_money', $money);
            $moneyLogic->addMoneyLog($userId, $userId, 4, 0, $money, $user['user_money']+$user['rebate_money']+$money, '用户退款');
            return 1;
        }
        return 2;
    }

    /**
     * 调用微信支付退款接口
     * @param $orderSn 订单唯一标识
     * @param $refundMoney 退款金额
     */
    public function refundByWeChat($orderSn, $refundMoney){
        vendor('WxPay');
        vendor('Wxpay.WxPay_Api.php');
        vendor('WxPay_Config.php');

//        return  array('msg'=>   \WxPayConfig::SSLKEY_PATH);
        $input = new \WxPayRefund();
//        out_refund_no、total_fee、refund_fee、op_user_id
        $input->SetOut_trade_no($orderSn);
        $input->SetOut_refund_no($orderSn);
        $input->SetTotal_fee($refundMoney*100);
        $input->SetRefund_fee($refundMoney*100);
        $input->SetOp_user_id(\WxPayConfig::MCHID);
        $result = \WxPayApi::refund($input);
        if($result['return_code'] == 'SUCCESS')
            return 1;
        return 2;
    }

}